﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using abp.Permissions;
using abp.Users;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;

namespace Vabp.Roles
{
    /// <summary>
    /// 角色
    /// </summary>
    public class LoginRole :AuditedAggregateRoot<int>
    {
        protected LoginRole()
        {
            
        }

        public LoginRole(string roleName,string displayName = null)
        {
            RoleName = roleName;
            displayName = displayName;
        }

        /// <summary>
        /// 角色名
        /// </summary>
        [Required]
        [MaxLength(25)]
        public string RoleName { get; set; }

        /// <summary>
        /// 显示名
        /// </summary>
        [MaxLength(50)]
        public string DisplayName
        {
            get
            {
                if (string.IsNullOrEmpty(DisplayName)) return RoleName;
                return DisplayName;
            }
            set => DisplayName = value;
        }

        public List<LoginUserRole> UserRoles { get; set; }


        ///// <summary>
        ///// 用户
        ///// </summary>
        //public IReadOnlyList<LoginUser> Users => users.AsReadOnly();

        public List<LoginPermissionGranted> Permissions { get; set; }

        public virtual void AddPermission(string permissionName, string displayName)
        {
            if (string.IsNullOrEmpty(permissionName)) throw new UserFriendlyException("无法添加权限,权限名称不能为空");
            if (Permissions != null && Permissions.Count > 0)
            {
                if (Permissions.Exists(p => p.PermissionName == permissionName)) throw new UserFriendlyException("无法添加权限,当前角色权限已经添加了");
            }
            (Permissions ?? new List<LoginPermissionGranted>()).Add(new LoginPermissionGranted(permissionName, displayName));
        }

        public virtual void RemovePermission(LoginPermissionGranted permission)
        {
            if (permission == null) throw new UserFriendlyException("权限移除失败,权限不能为空");
            if (Permissions == null || Permissions.Count <= 0 || !Permissions.Exists(r => r.PermissionName == permission.PermissionName))
                throw new UserFriendlyException("权限移除失败,当前权限已经移除,请刷新重试");
            Permissions.Remove(permission);
        }

    }
}
